/**
 * @author xxx
 * @time 2022-04-19 16PM
 * @description 对axios进行封装
 */
import axios from 'axios'
import store from '../store'
/* 通过创建axios实例对象，来进行通用数据封装 */
const Axios = axios.create({
    baseURL: '/aservice'
})

/**
 * 请求前的拦截
 */
Axios.interceptors.request.use(config => {
    let token = store.getters['common/token']
    /**
     * 做数据接口权限拦截
     */
    let _urls = ['/get/code','/login/byphone','/get/code','/register','/cart/add', '/cart/modify','/login']
    if (_urls.includes(config.url)) return config

    /** 返回错误信息 */
    if (!token) return Promise.reject({code: 400, message: '用户没有登录'})
    config.headers.token = token
    return config
})

Axios.interceptors.response.use(response => {
    /**
     * 判断是否是通用错误
     */
    let { data } = response
    if (data.code === 400) {
        alert(data.message)
        return Promise.reject(data)
    }

    return response
})

export default function(_request) {
    return new Promise(resolve => {
        Axios.request({
            url: _request.url,
            method: _request.method || 'post',
            data: _request.data || {},
            params: _request.params || {}
        }).then(({ data }) => {
            resolve(data)
        }).catch(e => {
            console.log(e)
            resolve({code: 800, message: '请求出错'})
        })
    })
}